#include					"SoundPacket.h"
#include					"Decoder.h"
#include					"byte.h"
#include					<iostream>

Decoder::Decoder() : _dec(NULL), _channel(2)
{

}

Decoder::~Decoder()
{
	if (_dec != NULL)
		opus_decoder_destroy(_dec);
}

void						Decoder::init()
{
	int						error = 0;
	if (_dec != NULL)
		opus_decoder_destroy(_dec);
	_dec = opus_decoder_create(48000, _channel, &error);
	if (error != OPUS_OK)
		std::cout << "error in opus_decoder_create" << std::endl;
}

void						Decoder::decode(IEncodedSoundPacket *encpacket, ISoundPacket *packet)
{
	int						size = 0;
	int						frame_size = opus_decoder_get_nb_samples(_dec, encpacket->data(), encpacket->len());
	int						channel_nb = opus_packet_get_nb_channels(encpacket->data());

	opus_int16				*output = new opus_int16[frame_size* channel_nb * sizeof(opus_int16)];
	size =  opus_decode(_dec, encpacket->data(), encpacket->len(), output, frame_size, 0);
	packet->setData(output);
	packet->setLen(size);
	packet->setFS(frame_size);
}

void						Decoder::decode(IOrder *order, ISoundPacket *packet)
{
	int						size = 0;
	short					*datasize = (short*)order->getData(sizeof(short));
	byte					*input = (byte*)order->getData(*datasize);
	int						frame_size = opus_decoder_get_nb_samples(_dec, input, *datasize);
	int						channel_nb = opus_packet_get_nb_channels(input);
	opus_int16				*output = new opus_int16[frame_size* channel_nb * sizeof(opus_int16)];

	size =  opus_decode(_dec, input, *datasize, output, frame_size, 0);
	packet->setData(output);
	packet->setLen(size);
	packet->setFS(frame_size);


}
